import requests
import concurrent.futures

from config import BAIDU_SPEECH_CONFIG

API_KEY = BAIDU_SPEECH_CONFIG['API_KEY']
SECRET_KEY = BAIDU_SPEECH_CONFIG['SECRET_KEY']
url = "https://tsn.baidu.com/text2audio"

def main(text):
    # 按句子分割文本
    chunks = split_text_by_sentence(text)
    
    # 合成音频并保存为临时文件
    temp_files = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = [executor.submit(synthesize, chunk) for chunk in chunks]
        for future in concurrent.futures.as_completed(futures):
            file_path = future.result()
            temp_files.append(file_path)

    # 读取未合并的二进制文件内容并返回列表
    binary_list = [read_binary_file(file_path) for file_path in temp_files]
    return binary_list

def split_text_by_sentence(text):
    sentences = text.split('. ')  # 假设以'. '作为句子分隔符，您可以根据实际情况调整
    return [sentence.strip() for sentence in sentences if sentence.strip()]

def synthesize(text):
    payload = 'tex={}&tok={}&cuid=MPfxtmFO7wx0Ft2W1fv3ttrPjdNEIMnI&ctp=1&lan=zh&spd=5&pit=5&vol=5&per=111&aue=6'.format(text, get_access_token())
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    file_path = "./audio/temp_output.wav"
    with open(file_path, 'wb') as f:
        f.write(response.content)
    # 对生成的音频文件进行简单的处理，裁剪开头和结尾的静音部分
    #process_audio(file_path)
    return file_path

def process_audio(file_path):
    # 这里需要使用适当的音频处理库来实现，例如 `pydub`
    # 以下是一个简单的示例，假设可以通过读取文件的一定字节来裁剪
    with open(file_path, 'rb') as f:
        data = f.read()
    start_index = 0
    for i in range(len(data)):
        if data[i]!= 0:  # 假设 0 表示静音，找到第一个非静音字节作为起始点
            start_index = i
            break
    end_index = len(data) - 1
    for i in range(len(data) - 1, 0, -1):
        if data[i]!= 0:  # 找到最后一个非静音字节作为结束点
            end_index = i
            break
    with open(file_path, 'wb') as f:
        f.write(data[start_index:end_index + 1])

def merge_audio_files(input_files, output_file):
    with open(output_file, 'wb') as output:
        for file_path in input_files:
            with open(file_path, 'rb') as input:
                output.write(input.read())

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

def read_binary_file(file_path):
    with open(file_path, 'rb') as f:
        return f.read()

if __name__ == '__main__':
    text = '听起来你昨天晚上度过了一段悠闲的时光。没有事情要做也是一种放松的方式，你可以自由地做自己想做的事情，或者什么都不做，享受宁静的时刻。那你昨天晚上都做了些什么呢？'
    binary_list = main(text)
  
    